import React, {useEffect, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {
  ProForm,
  ProFormSelect,
  ProFormText
} from "@ant-design/pro-form";
import styles from './style.less';
import {Card, Col, Form, message, Row, Select} from "antd";
import {UserManager, WorksManager} from "@/services/api-functions";
import UploadForm from "@/components/UploadForm";
import {AdminArticleModRequest, OssPojo} from "@/services/api-types";
// @ts-ignore
import {history} from "umi";
import {SYS_ENUMS} from "@/utils/constants";
import {richWordsNum} from "@/utils/office";
import AssociateSelect from "@/components/AssociateSelect/AssociateSelect";
import RichEditor from "@/components/RichEditor";


export const articleSaveOrUpdate = async (fields: any, select: any, content: string, cover: OssPojo|undefined,  resourcesAttachment: OssPojo|undefined, associated: any) => {
  try {
    const rpo: AdminArticleModRequest = {
      id: select?.id ?? '',
      cover,
      content,
      resourcesAttachment,
      labelList: fields.labels?.map((name: string)=>{return{id:'', name}}),
      title: fields.title,
      worksNature: fields.worksNature,
      userId: fields.userId,
      originalUrl: fields.originalUrl,
      copyrightType: fields.copyrightType,
      worksContentSize: richWordsNum(content)
    }
    if (associated) {
      rpo.associatedId = associated.id;
      rpo.associatedType = associated.type;
    }
    if (isSuccess((select && select.id ? (await WorksManager.articleEdit(rpo)) : (await WorksManager.articleAdd(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const ArticleEdit: React.FC<any> = ({match: {params: {id}}}) => {

  const [formRef] = Form.useForm()
  const [workNatureSelect, setWorkNatureSelect] = useState<any>(undefined)
  const [associated, setAssociated] = useState<any>(null);
  const [visible, setVisible] = useState<boolean>(false);
  const [article, setArticle] = useState<any>(null);
  const [cover, setCover] = useState<OssPojo>();
  const [resourcesAttachment, setResourcesAttachment] = useState<OssPojo>();
  // const [editorState, setEditorState] = useState<any>(BraftEditor.createEditorState("")) // 存储 editor 实例
  const [html, setHtml] = useState<any>() // 存储 editor 实例


  const queryArticleDetail = (id: any) => {
    if (id) {
      WorksManager.articleDetail(id).then(({code, data}) => {
        if (isSuccess(code)) {
          setArticle(data)
          if (data.cover) {
            setCover(data.cover)
          }
          if (data.resourcesAttachment) {
            setResourcesAttachment(data.resourcesAttachment)
          }
          if (data.worksNature) {
            setWorkNatureSelect(data.worksNature)
          }
          if(data.associated){
            setAssociated(data.associated)
          }
          // setEditorState(BraftEditor.createEditorState(data?.content ?? ''))
          setHtml(data?.content ?? '')
          formRef?.setFieldsValue({
            title: data.title,
            userId: data.userDto?.userId,
            cover: data.cover ? [data.cover] : [],
            resourcesAttachment: data.resourcesAttachment ? [data.resourcesAttachment] : [],
            labels: data?.labelList?.map((label: any) => label?.name) ?? [],
            worksNature: data.worksNature,
            originalUrl: data.originalUrl,
            copyrightType: data.copyrightType,
          })
        }
      })
    }
  }

  useEffect(() => {
    queryArticleDetail(id)
  }, [id])

  const onFinish = async (values: Record<string, any>) => {
    if (await articleSaveOrUpdate(values, article, html ?? '', cover, resourcesAttachment, associated)) {
      history.push('/article/list')
    }
  };

  return (
    <ProForm
      layout="vertical"
      hideRequiredMark
      submitter={{render: (props, dom) =><FooterToolbar>{dom}</FooterToolbar>,}}
      form={formRef}
      initialValues={{}}
      onFinish={onFinish}
      onValuesChange={v => {
        if(v.worksNature){
          setWorkNatureSelect(v.worksNature)
        }
      }}
    >
      <PageContainer>
        <Card title={`${id?'编辑':'添加'}文章`} className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormSelect label='所属设计师' name='userId' required rules={[{required: true, message: '请设置所属设计师',},]}
                             request={async (params) => {
                               const {code, data} = await UserManager.simpleUserQuery({
                                 current: 1,
                                 pageSize: 20,
                                 nickName: params.keyWords ?? '',
                               })
                               return isSuccess(code) ? (data.data ?? []).map((item: any) => {
                                 const {id, nickName, phone} = item
                                 return {label: `${nickName}(${phone ?? '暂无手机号'})`, value: id}
                               }) : []
                             }} showSearch/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormText label='文章标题' required rules={[{required: true, message: '请填写标题',},]} name="title"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <Form.Item label='文章内容' required>
                <RichEditor onChange={(html: any)=>{setHtml(html)}} initValue={article?.content??''} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm label='封面' name='cover' type='public' max={1} rules={[{required: true, message: '请上传封面',},]} required={true}
                          accept='.jpg,.jpeg,.bmp,.gif,.png' success={file => setCover(file)}
                          remove={() => setCover(undefined)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm label='附件' name='resourcesAttachment' type='formal' max={1} drag={true} preview='open'
                          success={file => setResourcesAttachment(file)} remove={() => setResourcesAttachment(undefined)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormSelect label='标签' name='labels' mode='tags'/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect label='原创分类' required rules={[{required: true, message: '请填选择原创分类',},]} name='worksNature'
                             initialValue={'ORIGINAL'}
                             options={Object.values(SYS_ENUMS.WORKS_NATURE).filter(nature => nature.value != 'COPY')}/>
            </Col>
          </Row>
          {
            workNatureSelect === 'SHARE' && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <ProFormText label='原文地址' name="originalUrl"/>
              </Col>
            </Row>
          }
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect label='版权声明' required rules={[{required: true, message: '请填选择版权声明',},]}
                             name='copyrightType'
                             initialValue={'WITHOUT_PERMISSION'}
                             options={Object.values(SYS_ENUMS.ARTICLE_COPYRIGHT_TYPE)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <Form.Item label='关联资源/文章'>
                <Select style={{width: '100%'}} onClick={() => setVisible(true)} placeholder='请选择'
                        value={associated ? associated.id : undefined}>
                  {
                    associated && <Select.Option value={associated.id}>{associated.title}</Select.Option>
                  }
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Card>
        <AssociateSelect useType='ARTICLE' initType='RESOURCES' visible={visible} title='请选择关联的资源/作品'
                         onCancel={() => setVisible(false)}
                         onSelect={(type: string, select: any) => setAssociated({
                           id: select.id,
                           title: select.title,
                           cover: select.cover,
                           type
                         })}/>
      </PageContainer>
    </ProForm>
  );
};

export default ArticleEdit;
